<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="网点" prop="networkPointsName">
            <el-input
                v-model="queryParams.networkPointsName"
                placeholder="请输入网点名称"
                clearable
            />
        </el-form-item>
        <el-form-item label="所属承运商:" prop="companyId">
            <el-select v-model="queryParams.companyId" filterable placeholder="请选择承运商" clearable>
                <el-option
                v-for="item in carrierList"
                :key="item.id"
                :label="item.companyName"
                :value="item.id">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="所在城市" prop="originPlace">
            <el-select v-model="queryParams.province" placeholder="请选择省"  style=" width:165px;"  @change="getCitys" clearable>
                <el-option v-for="item in provinces" :key="item.id" :label="item.cityName"
                    :value="item.id"></el-option>
            </el-select>

            <el-select v-model="queryParams.city" placeholder="请选择市" style=" width:165px;margin-left: 17px" clearable>
                <el-option v-for="item in queryCitys" :key="item.id" :label="item.cityName"
                    :value="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker clearable
            v-model="queryParams.createTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
            <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:menu:add']"
            >新增</el-button>
            <el-button
            type="primary"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="deleteIds"
            v-hasPermi="['system:menu:delete']"
            >删除</el-button>
            <el-button
            type="primary"
            plain
            icon="el-icon-s-check"
            size="mini"
            @click="examine(ids)"
            v-hasPermi="['system:menu:examine']"
            >审核</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="tagList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="网点名称" align="center" prop="networkPointsName"></el-table-column>
        <el-table-column label="负责人" align="center" prop="businessLeaderName"></el-table-column>
        <el-table-column label="负责人电话" align="center" prop="businessLeaderPhone"></el-table-column>
        <el-table-column label="是否审核" align="center" prop="isApproved">
            <template slot-scope="{row}">
                <span>{{ row.isApproved ? '是' : '否' }}</span>
            </template>
        </el-table-column>
        <el-table-column label="所在城市" align="center">
            <template slot-scope="{row}">
                <span>{{ fomatterAdressName(row.province) }} / {{ fomatterAdressName(row.city) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
            <template slot-scope="{row}">
                <span>{{ row.createTime && row.createTime.slice(0, 10) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
            <el-button
            type="text"
            plain
            icon="el-icon-s-check"
            size="mini"
            @click="handleUpdate(scope.row, '1')"
            v-if="!scope.row.isApproved"
            v-hasPermi="['system:menu:examine']"
            >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, '2')"
            v-hasPermi="['system:menu:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:menu:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
      </el-table>
      
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改标签管理对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
        <div v-if="isOpeartType == '1'" class="form-info">
            <div class="form-info-item">
                <span>*</span>
                网点名称: {{ form.companyName }}
            </div>
            <div class="form-info-item">
                <span>*</span>
                网点法人: {{ form.legalPersonName }}
            </div>
            <div class="form-info-item">
                <span>*</span>
                网点法人电话: {{ form.legalPersonPhone }}
            </div>
            <div class="form-info-item">
                <span>*</span>
                业务负责人姓名: {{ form.businessLeaderName }}
            </div>
            <div class="form-info-item">
                <span>*</span>
                业务负责人电话: {{ form.businessLeaderPhone }}
            </div>
            <div class="form-info-item">
                <span>*</span>
                紧急联系人电话: {{ form.emergencyContactPhone }}
            </div>
            <div class="form-info-item">
                <span>*</span>
                所属承运商: {{ componentName }}
            </div>
            <div class="form-info-item">
                <span>*</span>
                所在地址: {{ form.provinceName }} / {{  form.cityName }} / {{   form.districtName }}
            </div>
            <div class="form-info-item" v-if="form.businessLicense && form.businessLicense != ''">
                营业执照:
                <img :src="baseUrl + form.businessLicense" alt="">
            </div>
            <div class="form-info-item" v-if="form.roadTransportPermit && form.roadTransportPermit != ''">
                道路运输许可证:
                <img :src="baseUrl + form.roadTransportPermit" alt="">
            </div>
            <div class="form-info-item" v-if="(form.legalPersonIdCardFront && form.legalPersonIdCardFront != '') || (form.legalPersonIdCardBack && form.legalPersonIdCardBack != '')">
                身份证正反面:
                <img :src="baseUrl + form.legalPersonIdCardFront" alt="">
                <img :src="baseUrl + form.legalPersonIdCardBack" alt="">
            </div>
            <div class="form-info-item" v-if="(form.businessLeaderIdCardFront && form.businessLeaderIdCardFront != '') || (form.businessLeaderIdCardBack && form.businessLeaderIdCardBack != '')">
                业务负责人身份证正反面:
                <img :src="baseUrl + form.businessLeaderIdCardFront" alt="">
                <img :src="baseUrl + form.businessLeaderIdCardBack" alt="">
            </div>
            <div class="form-info-item" v-if="form.operationSitePhotos && form.operationSitePhotos != ''">
                经营场地及车辆照片:
                <img v-for="item in form.operationSitePhotos.split(',')" :key="item" :src="baseUrl + item" alt="">
            </div>
        </div>
        <el-form v-else ref="form" :model="form" :rules="rules" :inline="true" label-width="120px" class="form-inline">
            <el-form-item label="网点名称:" prop="networkPointsName">
                <el-input v-model="form.networkPointsName" placeholder="请输入网点名称" />
            </el-form-item>
            <el-form-item label="网点负责人:" prop="legalPersonName">
                <el-input v-model="form.legalPersonName" placeholder="请输入网点负责人" />
            </el-form-item>
            <el-form-item label="网点负责人电话:" prop="legalPersonPhone">
                <el-input v-model="form.legalPersonPhone" placeholder="请输入网点负责人电话" maxlength="11"/>
            </el-form-item>
            <el-form-item label="业务负责人姓名:" prop="businessLeaderName">
                <el-input v-model="form.businessLeaderName" placeholder="请输入业务负责人姓名" />
            </el-form-item>
            <el-form-item label="业务负责人电话:" prop="businessLeaderPhone">
                <el-input v-model="form.businessLeaderPhone" placeholder="请输入业务负责人电话" maxlength="11"/>
            </el-form-item>
            <el-form-item label="紧急联系人电话:" prop="emergencyContactPhone">
                <el-input v-model="form.emergencyContactPhone" placeholder="请输入紧急联系人电话" maxlength="11"/>
            </el-form-item>
            <el-form-item label="所属承运商:" prop="companyId">
                <el-select v-model="form.companyId" filterable placeholder="请选择承运商">
                    <el-option
                        v-for="item in carrierList"
                        :key="item.id"
                        :label="item.companyName"
                        :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所在地址:">
                <el-select v-model="form.province" placeholder="请选择省"  style=" width:165px;"  @change="getAddCitys" clearable>
                    <el-option v-for="item in provinces" :key="item.id" :label="item.cityName"
                      :value="item.id"></el-option>
                </el-select>

                <el-select v-model="form.city" placeholder="请选择市" style=" width:165px;margin-left: 17px"  @change="getAddregions" clearable>
                    <el-option v-for="item in addCitysList" :key="item.id" :label="item.cityName"
                        :value="item.id"></el-option>
                </el-select>

                <el-select v-model="form.district" placeholder="请选择区" style=" width:165px;margin-left: 17px"  clearable>
                    <el-option v-for="item in addRegionslist " :key="item.id" :label="item.cityName"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="营业执照:" prop="businessLicense">
                <image-upload v-model="form.businessLicense" :limit="1" />
            </el-form-item>
            <el-form-item label="道路运输许可证:" prop="roadTransportPermit">
                <image-upload v-model="form.roadTransportPermit" :limit="1"/>
            </el-form-item>
            <el-form-item label="身份证正反面:">
                <el-form-item label="正面" label-width="auto">
                    <image-upload v-model="form.legalPersonIdCardFront" :limit="1"/>
                </el-form-item>
                <el-form-item label="反面" label-width="auto">
                    <image-upload v-model="form.legalPersonIdCardBack" :limit="1"/>
                </el-form-item>
            </el-form-item>
            <el-form-item label="业务负责人身份证正反面:">
                <el-form-item label="正面" label-width="auto">
                    <image-upload v-model="form.businessLeaderIdCardFront" :limit="1"/>
                </el-form-item>
                <el-form-item label="反面" label-width="auto">
                    <image-upload v-model="form.businessLeaderIdCardBack" :limit="1"/>
                </el-form-item>
            </el-form-item>
            <el-form-item label="经营场地及车辆照片(最少6张):" prop="img">
                <image-upload v-model="form.operationSitePhotos" :limit="10"/>
            </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="isOpeartType == '2'">确 定</el-button>
        <el-button type="primary" @click="examine" v-else>审核</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import Enmu from "../../../../utils/enmu";
  import { getCompaniesListAll, getPointsList, addPointsList, editPoints, deletePoints, certificaPointsInfo } from "@/api/crm/settleIn";
  import { listChina } from "@/api/crm/china";
  import {forrmatterEnmu} from "@/utils/index"
  var validatePass = (rule, value, callback) => {
    if (value) {
        let r = /^1[34578]\d{9}$/.test(value);
        if(!r) {
            callback(new Error('请输入正确的手机号码'));
        } else {
            callback();
        }
    } else {
        callback();
    }
};
  export default {
    name: "Tag",
    data() {
      return {
        baseUrl: process.env.VUE_APP_BASE_API,
        provinces: [],
        cityslist: [],
        regionslist: [],
        queryCitys: [],
        addCitysList: [],
        addRegionslist: [],
        // 承运商列表
        carrierList: [],
        Enmu,
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 标签管理表格数据
        tagList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
            companyId: '',
            province: '',
            city: '',
            createTime: '',
            networkPointsName: ''
        },
        form: {
            networkPointsName: '',
            legalPersonName: '',
            legalPersonPhone: '',
            businessLeaderName: '',
            businessLeaderPhone: '',
            emergencyContactPhone: '',
            province: '',
            city: '',
            district: '',
            businessLicense: '',
            roadTransportPermit: '',
            legalPersonIdCardFront: '',
            legalPersonIdCardBack: '',
            businessLeaderIdCardFront: '',
            businessLeaderIdCardBack: '',
            operationSitePhotos: '',
            companyId: ''
        },
        rules: {},
        ids: [],
        isOpeartType: 2,
        allCityList: []
      };
    },
    created() {
      this.getList();
      this.getlistChina();
      this.getCarrierList();
    },
    computed: {
        formRule() {
            // 1 审核 2 修改
            if(this.isOpeartType == '1') {
                return this.examineRule();
            } else {
                return this.editRule();
            }
        },
        componentName() {
            let i = this.carrierList.findIndex(ele => ele.id == this.form.companyId);
            return i > -1 ? this.carrierList[i].companyName : this.form.id
        }
    },
    methods: {
        forrmatterEnmu,
        getlistChina() {
            var queryParams1 = {
                pageNum: 1,
                pageSize: 10000,
            };
            listChina(queryParams1).then(response => {
                this.allCityList = response.rows;
                this.provinces = response.rows.filter(item => item.depth == 1);
                this.cityslist = response.rows.filter(item => item.depth == 2);
                this.regionslist = response.rows.filter(item => item.depth == 3);
            });
        },
        getCitys(value) {
            this.queryCitys = this.cityslist.filter(item => parseInt(item.parentId) == parseInt(value));
            this.queryParams.city = '';
        },
        getAddCitys(value) {
            this.addCitysList = this.cityslist.filter(item => parseInt(item.parentId) == parseInt(value));
            this.form.city = '';
            this.form.district = '';
        },
        getAddregions(value) {
            this.addRegionslist = this.regionslist.filter(item => parseInt(item.parentId) == parseInt(value));
            this.form.district = '';
        },
        // 省市区转换成中文
        fomatterAdressName(code) {
            if(!code || code == "") return "";
          let index = this.allCityList.findIndex(ele => ele.id == code);
          return index > -1 ? this.allCityList[index].cityName : code;
        },
        getCarrierList() {
            getCompaniesListAll().then(res => {
                this.carrierList = res.rows.map((ele) => {
                    return {
                        id: ele.id,
                        companyName: ele.companyName
                    }
                });
            })
        },
      /** 查询标签管理列表 */
      getList() {
        this.loading = true;
        getPointsList(this.queryParams).then(response => {
          this.tagList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
    reset() {
        console.log("000")
      this.form = {
            id: '',
            networkPointsName: '',
            legalPersonName: '',
            legalPersonPhone: '',
            businessLeaderName: '',
            businessLeaderPhone: '',
            emergencyContactPhone: '',
            province: '',
            city: '',
            district: '',
            businessLicense: '',
            roadTransportPermit: '',
            legalPersonIdCardFront: '',
            legalPersonIdCardBack: '',
            businessLeaderIdCardFront: '',
            businessLeaderIdCardBack: '',
            operationSitePhotos: '',
            companyId: ''
      };
      this.resetForm("form");
    },
    handleDelete(row) {
        this.$confirm('确定删除此承运商', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            deletePoints([row.id]).then(res => {
                if(res.code == 200) {
                    this.$modal.msgSuccess("删除成功");
                    this.getList();
                }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    handleUpdate(row, flag) {
        this.isOpeartType = flag;
        Object.keys(this.form).forEach(ele => {
            if(ele == 'province' || ele == 'city' || ele == 'district') {
                if(row[ele] && row[ele] != '' && row[ele] != null) {
                    this.$set(this.form, ele, row[ele] - 0);
                }
            } else {
                this.$set(this.form, ele, row[ele]);
            }  
        });
        this.addCitysList = this.cityslist.filter(item => parseInt(item.parentId) == parseInt(this.form.province));
        this.addRegionslist = this.regionslist.filter(item => parseInt(item.parentId) == parseInt(this.form.city));
        this.$set(this.form, 'id', row.id);
        if(flag == '1') {
            this.$set(this.form, 'provinceName', this.fomatterAdressName(row.province));
            this.$set(this.form, 'cityName', this.fomatterAdressName(row.city));
            this.$set(this.form, 'districtName', this.fomatterAdressName(row.district));
        }
        this.open = true;
    },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      handleAdd() {
        this.reset();
        this.open = true;
      },
      submitForm() {
            console.log(this.form);
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if(this.form.id !== '') {
                        editPoints(this.form).then(res => {
                            if(res.code == 200) {
                                this.$modal.msgSuccess("修改成功成功");
                                this.open = false;
                                this.getList();
                                this.reset();
                            }
                        })
                    } else {
                        addPointsList(this.form).then(res => {
                            if(res.code == 200) {
                                this.$modal.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                                this.reset();
                            }
                        })
                    }
                } else {
                    return false;
                }
            });
            
            
        },
        editRule() {
        return {
            legalPersonPhone: [
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
            businessLeaderPhone: [
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
            emergencyContactPhone: [
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
        }
      },
      examineRule() {
        let rule = {
            companyName: [
                { required: true, message: '请输入承运商名称', trigger: 'change' }
            ],
            legalPersonName: [
                { required: true, message: '请输入承运商法人', trigger: 'change' }
            ],
            legalPersonPhone: [
                { required: true, message: '请输入承运商法人电话', trigger: 'change' },
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
            businessLeaderName: [
                { required: true, message: '请输入业务负责人姓名', trigger: 'change' }
            ],
            businessLeaderPhone: [
                { required: true, message: '请输入业务负责人电话', trigger: 'change' },
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
            emergencyContactPhone: [
                { required: true, message: '请输入紧急联系人电话', trigger: 'change' },
                { min: 11, max: 11, message: '请输入11位数字', trigger: 'blur' },
                { validator: validatePass, trigger: 'blur' }
            ],
            province: [
                { required: true, message: '请选择省', trigger: 'change' }
            ],
            city: [
                { required: true, message: '请选择市', trigger: 'change' }
            ],
            district: [
                { required: true, message: '请选择区', trigger: 'change' }
            ],
        };
        return rule;
      },
      checkoutAdmin() {
        let keys = ['companyName', 'legalPersonName', 'legalPersonPhone', 'businessLeaderName', 'companyId', 'businessLeaderPhone', 'emergencyContactPhone', 'province', 'city', 'district'];
        for(let i = 0; i < keys.length; i++) {
            if(this.form[keys[i]] == "") {
                this.$modal.msgError("必填项不能为空，请修改必填项");
                return false;
            }
        }
        return true;
      },
        // 审核
        examine(ids) {
            if(!this.checkoutAdmin()) return;
            certificaPointsInfo({id: this.form.id }).then(res => {
                if(res.code == 200) {
                    this.$modal.msgSuccess("审核成功");
                    this.open = false;
                    this.getList();
                    this.reset();
                }
            })
        },
         // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
      },
      deleteIds() {
        this.$confirm('确定删除所购选的承运商', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            deletePoints(this.ids).then(res => {
                if(res.code == 200) {
                    this.$modal.msgSuccess("删除成功");
                    this.getList();
                }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
    },
     
    
  };
  </script>
  <style scoped>
  .form-inline {
    display: flex;
    flex-wrap: wrap;
  }
  .form-info {
    display: flex;
    width: 800px;
    flex-wrap: wrap;
  }
  .form-info-item {
    width: 49%;
    flex: 0 0 49%;
    height: 40px;
  }
  .form-info-item span {
    color: red;
  }
  .form-info-item img {
    width: 100px;
    height: 100px;
    vertical-align: top;
    margin-right: 10px;
  }
  </style>
  